package com.youmingxing.fragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.youmingxing.AllStarApp;
import com.youmingxing.R;
import com.youmingxing.activity.ContentDetailActivity;
import com.youmingxing.activity.MainActivity;
import com.youmingxing.activity.WorksCommitGuideActivity;
import com.youmingxing.activity.selfInfo.AboutAppActivity;
import com.youmingxing.activity.selfInfo.AccountSettingActivity;
import com.youmingxing.activity.selfInfo.CertificationActivity;
import com.youmingxing.activity.selfInfo.CertificationingActivity;
import com.youmingxing.activity.selfInfo.EventsCardActivity;
import com.youmingxing.activity.selfInfo.FansActivity;
import com.youmingxing.activity.selfInfo.FeedbackActivity;
import com.youmingxing.activity.selfInfo.MyAllAuditionsActivity;
import com.youmingxing.activity.selfInfo.MyAllWorksActivity;
import com.youmingxing.activity.selfInfo.MyAuditionEndActivity;
import com.youmingxing.activity.selfInfo.MyAuditionGoingActivity;
import com.youmingxing.activity.selfInfo.MyFocusActivity;
import com.youmingxing.activity.selfInfo.MyTicketsActivity;
import com.youmingxing.activity.selfInfo.PersonalInfoActivity;
import com.youmingxing.activity.selfInfo.PopularityActivity;
import com.youmingxing.adpter.RecyclerViewAdapter.MyContentAdapter;
import com.youmingxing.bean.Content;
import com.youmingxing.bean.selfinfo.PersonalInfo;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.dialog.LoginDialog;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.utils.StatusUtil;

import org.json.JSONException;
import org.json.JSONObject;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * A simple {@link Fragment} subclass.
 */
public class SelfInfoFragment extends Fragment implements View.OnClickListener {

    private View view;
    private ImageView userIcon;
    private ImageView backgroundImg;
    private TextView userName;
    private TextView userSignature;
    //    private LinearLayout horizontalView;
    private RecyclerView horizontalView;
    PersonalInfo myInfo;
    /**
     * *我的活动**
     */
    private TextView auditionNameTv;
    private TextView auditionTitle;
    private TextView auditionStatus;
    private TextView auditionTicket;
    private View auditionContent;
    private ImageView auditionImage;
    private TextView noAuditionIndicator;
    private TextView auditionRankTv;
    private TextView auditionMoreTv;
    private ImageView auditionBadge;
    /**
     * *我的动态**
     */
    private TextView workMoreTv;
    private TextView noWorkIndicator;
    private TextView noWorkTv;
    /**
     * *实名认证**
     */
    private RelativeLayout certificationRL;
    private TextView certificationStatusTv;
    private ImageView realAuthBadge;
    /**
     * *关于合作**
     */
    private RelativeLayout cooperationRL;

    /**
     * *帐号设置**
     */
    private RelativeLayout accountsRL;
    private ImageView accountQQ;
    private ImageView accountWeibo;
    private ImageView accountWechat;
    private ImageView accountMobile;

    /**
     * 活动卡券
     */
    private RelativeLayout cardRL;

    /**
     * *意见反馈**
     */
    private RelativeLayout feedbackRl;

    private LinearLayout myPopularityLL;
    private TextView myPopularityNumTv;

    private LinearLayout myTicketLL;
    private TextView myTicketNumTv;


    private RelativeLayout myAudition;

    private LinearLayout myfansLL;
    private TextView myfansNumTv;
    private LinearLayout myfocusLL;
    private TextView myfocusNumTv;

    /**
     * 有新版本升级
     */
    private RelativeLayout updateLayout;
    private Context appContext = AllStarApp.getInstance();


    public SelfInfoFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_self_info, container, false);
            initView(view);
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!GlobalDataManager.token.isEmpty()) {
            //显示缓存中的信息
            if (!GlobalDataManager.userInfo.isEmpty()) {
                try {
                    JSONObject json = new JSONObject(GlobalDataManager.userInfo);
                    myInfo = new PersonalInfo(json.optJSONObject("data"));
                    updateView();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            //从服务器获取新的
            getDataFromServer();
        } else {
            myInfo = null;
            updateView();
        }
    }

    private void getDataFromServer() {
        SelfInfoApi.getSelfInfo(new BaseJsonHandler(getContext()) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                myInfo = new PersonalInfo(response.optJSONObject("data"));
                //更新本地缓存
                GlobalDataManager.userInfo = response.toString();
                GlobalDataManager.save();
                updateView();
            }
        });
    }

    public void initView(View view) {
        //背景
        backgroundImg = (ImageView) view.findViewById(R.id.bg_img);
        Glide.with(appContext).load(GlobalDataManager.backgroundImg).into(backgroundImg);
        view.findViewById(R.id.my_message).setOnClickListener(this);

        userIcon = (ImageView) view.findViewById(R.id.img_avatar);
        userName = (TextView) view.findViewById(R.id.tv_name);
        userSignature = (TextView) view.findViewById(R.id.usersignature);
        //活动
        auditionContent = view.findViewById(R.id.audition_content_rl);
        auditionTicket = (TextView) view.findViewById(R.id.audition_ticket);
        auditionTitle = (TextView) view.findViewById(R.id.audition_title);
        auditionStatus = (TextView) view.findViewById(R.id.audition_status);
        auditionNameTv = (TextView) view.findViewById(R.id.audition_name);
        auditionImage = (ImageView) view.findViewById(R.id.auditions_icon);
        auditionRankTv = (TextView) view.findViewById(R.id.audition_rank);
        noAuditionIndicator = (TextView) view.findViewById(R.id.audition_indicator);
        auditionMoreTv = (TextView) view.findViewById(R.id.auditions_more);
        myAudition = (RelativeLayout) view.findViewById(R.id.auditions_new);
        auditionBadge = (ImageView) view.findViewById(R.id.audition_badge);
        //我的作品
        workMoreTv = (TextView) view.findViewById(R.id.work_more_tv);
        noWorkIndicator = (TextView) view.findViewById(R.id.my_work_indicator);
        noWorkTv = (TextView) view.findViewById(R.id.my_work_no_data_tv);
        horizontalView = (RecyclerView) view.findViewById(R.id.id_recyclerview_horizontal);
        noWorkIndicator.setOnClickListener(this);
        //实名认证
        certificationRL = (RelativeLayout) view.findViewById(R.id.certification_rl);
        certificationStatusTv = (TextView) view.findViewById(R.id.certification_status);
        realAuthBadge = (ImageView) view.findViewById(R.id.real_auth_badge);
        //账号设置
        accountsRL = (RelativeLayout) view.findViewById(R.id.accounts_rl);
        accountQQ = (ImageView) view.findViewById(R.id.account_qq);
        accountWeibo = (ImageView) view.findViewById(R.id.account_weibo);
        accountWechat = (ImageView) view.findViewById(R.id.account_wechat);
        accountMobile = (ImageView) view.findViewById(R.id.account_mobile);

        // 活动卡券
        cardRL = (RelativeLayout) view.findViewById(R.id.card_rl);

        //关于合作
        cooperationRL = (RelativeLayout) view.findViewById(R.id.cooperation_rl);
        //反馈
        feedbackRl = (RelativeLayout) view.findViewById(R.id.feedback_rl);
        updateLayout = (RelativeLayout) view.findViewById(R.id.need_update_layout);
        myPopularityLL = (LinearLayout) view.findViewById(R.id.my_popularity_ll);
        myTicketLL = (LinearLayout) view.findViewById(R.id.my_ticket_ll);
        myfansLL = (LinearLayout) view.findViewById(R.id.myfans_ll);
        myfocusLL = (LinearLayout) view.findViewById(R.id.myfocus_ll);

        myPopularityNumTv = (TextView) view.findViewById(R.id.my_popularity_num);
        myTicketNumTv = (TextView) view.findViewById(R.id.my_ticket_num);
        myfansNumTv = (TextView) view.findViewById(R.id.myfans_num);
        myfocusNumTv = (TextView) view.findViewById(R.id.myfocus_num);

        userIcon.setOnClickListener(this);//  登录
        auditionMoreTv.setOnClickListener(this);//  我的活动
        myAudition.setOnClickListener(this);  //去参加活动
        workMoreTv.setOnClickListener(this); //  动态
        certificationRL.setOnClickListener(this);//  实名认证
        accountsRL.setOnClickListener(this); //  帐号设置
        cardRL.setOnClickListener(this); //  卡券活动
        cooperationRL.setOnClickListener(this);//  关于合作
        feedbackRl.setOnClickListener(this);  //  反馈
        myPopularityLL.setOnClickListener(this);// 人气
        myTicketLL.setOnClickListener(this); //  加油票
        myfansLL.setOnClickListener(this);//  粉丝
        myfocusLL.setOnClickListener(this);  //关注
    }

    private void updateView() {
        if (myInfo == null) {
            //未登录的ui样式
            //Top
            userIcon.setImageResource(R.drawable.default_avatar);
            userName.setText(R.string.selfinfo_hint_not_login);
            myPopularityNumTv.setText("0");
            myTicketNumTv.setText("0");
            myfansNumTv.setText("0");
            myfocusNumTv.setText("0");
            certificationStatusTv.setText(R.string.certification_no);

            //我的活动
            noAuditionIndicator.setVisibility(View.VISIBLE);
            noAuditionIndicator.setText("去登录");
            auditionNameTv.setText("登录后可报名参加活动");
            auditionMoreTv.setVisibility(View.GONE);
            auditionContent.setVisibility(View.GONE);
            auditionImage.setImageResource(R.drawable.default_16_9);
            auditionBadge.setVisibility(View.GONE);

            //我的作品
            noWorkIndicator.setVisibility(View.VISIBLE);
            workMoreTv.setVisibility(View.INVISIBLE);
            noWorkIndicator.setText("去登录");
            noWorkTv.setVisibility(View.VISIBLE);
            noWorkTv.setText("登录后可发布作品");
            horizontalView.setVisibility(View.INVISIBLE);

            //账号设置
            accountQQ.setImageResource(R.mipmap.no_qq);
            accountWechat.setImageResource(R.mipmap.no_wechat);
            accountWeibo.setImageResource(R.mipmap.no_weibo);
            accountMobile.setImageResource(R.mipmap.no_tel);
            return;
        }
        userName.setText(myInfo.nickname);
        Glide.with(appContext).load(myInfo.headimg)
                .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                .bitmapTransform(new CropCircleTransformation(appContext)).crossFade().into(userIcon);
        myPopularityNumTv.setText(myInfo.popularity + "");
        myTicketNumTv.setText(myInfo.support_ticket + "");
        myfansNumTv.setText(myInfo.follower + "");
        myfocusNumTv.setText(myInfo.follow + "");

        //我的活动
        if (myInfo.latestAudition != null) {
            //有活动信息
            noAuditionIndicator.setText("");
            Glide.with(appContext).load(myInfo.latestAudition.category_img)
                    .placeholder(R.drawable.default_16_9).error(R.drawable.default_16_9)
                    .animate(R.anim.abc_fade_in).into(auditionImage);
            if (myInfo.haveMoreAutidion) {
                auditionMoreTv.setVisibility(View.VISIBLE);
            }
            auditionContent.setVisibility(View.VISIBLE);
            auditionNameTv.setText("");
            auditionTitle.setText(myInfo.latestAudition.audition_title);
            auditionStatus.setText(myInfo.latestAudition.status_tip);
            auditionRankTv.setText("活动排名:" + myInfo.latestAudition.rank + "");
            auditionTicket.setText("收到票数:" + myInfo.latestAudition.votes + "");
            if (myInfo.auditions_badge == 0) {
                auditionBadge.setVisibility(View.GONE);
                if (myInfo.real_auth_badge == 0) {
                    ((MainActivity) getActivity()).setTabBadge(3, false);
                }
            } else {
                auditionBadge.setVisibility(View.VISIBLE);
                ((MainActivity) getActivity()).setTabBadge(3, true);
            }

        } else {
            //无活动信息
            auditionBadge.setVisibility(View.GONE);
            noAuditionIndicator.setVisibility(View.VISIBLE);
            noAuditionIndicator.setText("去报名");
            auditionMoreTv.setVisibility(View.GONE);
            auditionContent.setVisibility(View.GONE);
            auditionNameTv.setText(R.string.no_audition_please_sign_up);
            auditionImage.setImageResource(R.drawable.default_16_9);

        }
        //我的作品
        if (myInfo.myContents.size() == 0) {
            //无作品
            workMoreTv.setVisibility(View.INVISIBLE);
            noWorkIndicator.setVisibility(View.VISIBLE);
            noWorkIndicator.setText("发布新作品");
            noWorkTv.setVisibility(View.VISIBLE);
            noWorkTv.setText("您还没有发布过任何作品哦");
            horizontalView.setVisibility(View.INVISIBLE);
        } else {
            workMoreTv.setVisibility(View.VISIBLE);
            noWorkTv.setVisibility(View.GONE);
            noWorkIndicator.setVisibility(View.GONE);
            horizontalView.setVisibility(View.VISIBLE);
            //设置布局管理器
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(appContext);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            horizontalView.setLayoutManager(linearLayoutManager);
            //设置适配器
            MyContentAdapter mAdapter = new MyContentAdapter(appContext, myInfo.myContents);
            horizontalView.setAdapter(mAdapter);
            mAdapter.setOnItemClickLitener(
                    new MyContentAdapter.OnItemClickLitener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            if (position == 0) {
                                showNewWorkDialog();
                            } else {
                                final Content content = myInfo.myContents.get(position);
                                if (content.status != 2) {
                                    Intent intent = new Intent(getContext(), ContentDetailActivity.class);
                                    intent.putExtra("content_id", content.getId());
                                    getContext().startActivity(intent);
                                } else {
                                    //删除
                                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                    builder.setTitle(R.string.delete_not_pass_work_title).setMessage
                                            (content.reason)
                                            .setPositiveButton(R.string.delete_not_pass_work_yes, new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    SelfInfoApi.deleteMyWorks(content.getId(), new
                                                            BaseJsonHandler(getActivity()) {
                                                                @Override
                                                                public void onSuccessWithData(JSONObject response) {
                                                                    Toast.makeText(getActivity(), R.string
                                                                            .delete_work_success, Toast.LENGTH_SHORT).show();
                                                                    getDataFromServer();
                                                                }
                                                            });
                                                }
                                            }).setNegativeButton(R.string.delete_not_pass_work_no, null).show();

                                }
                            }
                        }
                    }

            );
        }

        //实名认证
        certificationStatusTv.setText(StatusUtil.parseCertificationStatus(myInfo.real_auth_status));
        if (myInfo.real_auth_badge == 0) {
            realAuthBadge.setVisibility(View.GONE);
            if (myInfo.auditions_badge == 0) {
                ((MainActivity) getActivity()).setTabBadge(3, false);
            }
        } else {
            realAuthBadge.setVisibility(View.VISIBLE);
            ((MainActivity) getActivity()).setTabBadge(3, true);
        }
        //绑定信息
        if (myInfo.bindQQ) {
            accountQQ.setImageResource(R.mipmap.have_qq);
        } else {
            accountQQ.setImageResource(R.mipmap.no_qq);
        }
        if (myInfo.bindWechat) {
            accountWechat.setImageResource(R.mipmap.have_wechat);
        } else {
            accountWechat.setImageResource(R.mipmap.no_wechat);
        }
        if (myInfo.bindWeibo) {
            accountWeibo.setImageResource(R.mipmap.have_weibo);
        } else {
            accountWeibo.setImageResource(R.mipmap.no_weibo);
        }
        if (myInfo.bindMobile) {
            accountMobile.setImageResource(R.mipmap.have_tel);
        } else {
            accountMobile.setImageResource(R.mipmap.no_tel);
        }

        //检测升级
        if (GlobalDataManager.needUpdate) {
            updateLayout.setVisibility(View.VISIBLE);
            updateLayout.setOnClickListener(this);
        } else {
            updateLayout.setVisibility(View.GONE);
        }
    }

    private void showNewWorkDialog() {
        Intent intent = new Intent(getActivity(), WorksCommitGuideActivity.class);
        startActivity(intent);
    }

    private void showLoginDialog() {
        Intent intent = new Intent(getActivity(), LoginDialog.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if (GlobalDataManager.token.isEmpty() && v.getId() != R.id.cooperation_rl && v.getId() != R.id.feedback_rl) {
            showLoginDialog();
            return;
        }
        Intent intent;
        switch (v.getId()) {
            case R.id.img_avatar:
                if (GlobalDataManager.token.isEmpty()) {
                    showLoginDialog();
                } else {
                    intent = new Intent(getActivity(), PersonalInfoActivity.class);
                    intent.putExtra("u_id", GlobalDataManager.userId);
                    startActivity(intent);
                }
                break;
            case R.id.my_popularity_ll:
                intent = new Intent(getActivity(), PopularityActivity.class);
                startActivity(intent);
                break;
            case R.id.my_ticket_ll:
                intent = new Intent(getActivity(), MyTicketsActivity.class);
                startActivity(intent);
                break;
            case R.id.my_message:
//                intent = new Intent(getActivity(), MessageListActivity.class);
//                startActivity(intent);
                break;
            case R.id.myfans_ll:
                intent = new Intent(getActivity(), FansActivity.class);
                startActivity(intent);
                break;
            case R.id.myfocus_ll: //  我关注的
                intent = new Intent(getActivity(), MyFocusActivity.class);
                startActivity(intent);
                break;
            case R.id.auditions_more: //  我的 全部 活动
                intent = new Intent(getActivity(), MyAllAuditionsActivity.class);
                intent.putExtra(MyAllAuditionsActivity.EXTRAS_USER_ID, GlobalDataManager.userId);
                startActivity(intent);
                break;
            case R.id.auditions_new: //  我的  活动
                if (myInfo == null) {
                    return;
                }
                if (myInfo.latestAudition == null) {
                    //没有活动,去首页
                    ((MainActivity) getActivity()).setTab(0);
                    return;
                }
                if (myInfo.latestAudition.status == 0) {
                    intent = new Intent(getActivity(), MyAuditionGoingActivity.class);
                } else {
                    intent = new Intent(getActivity(), MyAuditionEndActivity.class);
                }
                intent.putExtra("id", myInfo.latestAudition.id);
                startActivity(intent);
                break;
            case R.id.work_more_tv: //  我的  动态
                intent = new Intent(getActivity(), MyAllWorksActivity.class);
                intent.putExtra("u_id", GlobalDataManager.userId);
                startActivity(intent);
                break;
            case R.id.my_work_indicator:
                //没有作品
                if (GlobalDataManager.token.equals("")) {

                }
                showNewWorkDialog();
                break;
            case R.id.certification_rl: //  认证
                if (myInfo.real_auth_status == 0) {
                    intent = new Intent(getActivity(), CertificationActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getActivity(), CertificationingActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.accounts_rl: //  帐号设置
                intent = new Intent(getActivity(), AccountSettingActivity.class);
                intent.putExtra("is_show_edit_pwd", myInfo.bindMobile);
                startActivity(intent);
                break;

            case R.id.card_rl:  //活动卡券
                intent = new Intent(getActivity(), EventsCardActivity.class);
                startActivity(intent);
                break;

            case R.id.cooperation_rl:  //关于合作
                intent = new Intent(getActivity(), AboutAppActivity.class);
                startActivity(intent);

                break;
            case R.id.feedback_rl:
                intent = new Intent(getActivity(), FeedbackActivity.class);
                startActivity(intent);
                break;
            case R.id.need_update_layout:
                ((MainActivity) getActivity()).showUpdateDialog();
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
    }

}
